<template>
  <div>
    <a-row class="container">
      <div class="sp">
        <div class="sp_left">
          <div class="sp_left_action">
            <svg @click="addCampusVisible = true">
              <use
                xlink:href="../../../../assets/img/icons/all.svg#icon-plus"
              ></use>
            </svg>
          </div>
          <div class="sp_left_text">校区：</div>
        </div>

        <div class="sp_right">
          <a-spin :spinning="Tree_spin_status" tip="Loading...">
            <div
              class="sp_right_item"
              v-for="(campus, index) in campusList"
              :key="index"
              style="float: left"
            >
              <div v-if="!campus.isEditing" class="sp_right_item_campusBtn" name="campusBtn">
                <span
                  class="sp_right_show_campusBtn"
                  @click="campusSelect(campus, index)"
                >
                  {{ campus.campus_name }}
                  <!-- 设置无法编辑 -->
                  <!-- <a-icon type="edit" @click="editCampus(index)" /> -->
                  <!-- <a-popconfirm
                    placement="topLeft"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="deleteCampus(index, campus)"
                  >
                    <template slot="title">
                      <p>你确定要删除这个校区吗？</p>
                    </template>
                    <a-icon type="close" />
                  </a-popconfirm> -->
                </span>
              </div>
              <div v-else>
                <span style="font-size: 15px ;">
                  <input
                    type="text"
                    placeholder="校区名不能为空"
                    v-model="campus.campus_name"
                    class="editText"
                  />
                  <a-icon type="check" @click="endEditCampus(index, campus)" />
                </span>
              </div>
            </div>
          </a-spin>
        </div>
      </div>
      <div class="building">
        <div class="building_left">
          <div class="building_left_action">
            <svg @click="addBuildingVisible = true">
              <use
                xlink:href="../../../../assets/img/icons/all.svg#icon-plus"
              ></use>
            </svg>
          </div>
          <div class="building_left_text">
            建筑（{{ this.campusSelected.campus_name }}共{{
              this.buildingList.length
            }}条记录）
          </div>
        </div>
      </div>
      <div>
        <space-tree
          @tellFather="fatherEmit"
          class="class-card"
          :buildingProp="buildingList"
        ></space-tree>
      </div>
      <div class="room">
        <div class="room_left">
          <div class="room_left_action">
            <svg @click="addRoomVisible = true">
              <use
                xlink:href="../../../../assets/img/icons/all.svg#icon-plus"
              ></use>
            </svg>
          </div>
          <div class="room_left_text">
            房间（共{{ this.roomList.length }}条记录）
          </div>
        </div>
      </div>
      <div>
        <space-card
          class="class-card"
          :roomsProp="roomList"
          :buildingName="value"
        ></space-card>
      </div>
    </a-row>
    <!-- 添加房间 -->
    <a-modal
      v-model="addRoomVisible"
      title="添加房间"
      @ok="submitAddRoom"
      :maskClosable="false"
    >
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="学校">
          {{ orgName }}
        </a-form-model-item>
        <a-form-model-item label="校区建筑">
          <a-tree-select
            :value="selectValue"
            allow-clear
            tree-default-expand-all
            @change="campusAndBuilding"
          >
            <a-tree-select-node
              :selectable="false"
              :key="campus.campus_name"
              :value="`${campus._id}#`"
              :title="campus.campus_name"
              v-for="campus in campusList"
            >
              <a-tree-select-node
                :key="buildings.building_name"
                :value="`${campus.campus_name}:${buildings.building_name}`"
                :title="buildings.building_name"
                v-for="buildings in campus.buildings"
              >
              </a-tree-select-node>
            </a-tree-select-node>
          </a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="房间类型">
          <a-select v-model="roomForm.room_type">
            <a-select-option
              v-for="room_type in roomTypes"
              :key="room_type"
              :value="room_type"
            >
              {{ room_type }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="房间名">
          <a-input
            placeholder="请输入房间名"
            v-model="roomForm.room_name"
          ></a-input>
        </a-form-model-item>
        <a-form-model-item label="房间号">
          <a-input
            placeholder="请输入房间号"
            v-model="roomForm.room_number"
          ></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 添加校区 -->
    <a-modal
      v-model="addCampusVisible"
      title="添加校区"
      @ok="submitAddCampus"
      :maskClosable="false"
    >
      <a-form-model
        :model="campusForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="campusFormRules"
      >
        <a-form-model-item label="学校名称">
          {{ orgName }}
        </a-form-model-item>
        <a-form-model-item label="校区名称" prop="campusName">
          <a-input
            placeholder="请输入校区名称"
            v-model="campusForm.campus_name"
          ></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 添加建筑 -->
    <a-modal
      v-model="addBuildingVisible"
      title="添加建筑"
      @ok="submitAddBuilding"
      :maskClosable="false"
    >
      <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="学校">
          {{ orgName }}
        </a-form-model-item>
        <a-form-model-item label="校区">
          <a-select v-model="buildingForm.campus_name">
            <a-select-option v-for="item in campusList" :key="item.campus_name">
              {{ item.campus_name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="建筑类型">
          <a-select v-model="buildingForm.building_type">
            <a-select-option
              v-for="buildingType in buildingTypes"
              :key="buildingType.value"
              :value="buildingType.value"
            >
              {{ buildingType.key }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="建筑名">
          <a-input
            placeholder="请输入建筑名"
            v-model="buildingForm.building_name"
          ></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <batchAddSpace :visible.sync="bulkImport_visible"></batchAddSpace>
  </div>
</template>

<script>
import SpaceCard from "./SpaceCard";
import SpaceTree from "./SpaceTree";
import BatchAddSpace from "./BatchAddSpace";
import axiosInstance from "@/utils/axios";
import { mapState } from "vuex";

export default {
  components: { SpaceCard, SpaceTree, BatchAddSpace },
  data() {
    return {
      selectValue: undefined,
      buildingTypes: [
        { key: "教学楼", value: "classroom" },
        { key: "实验楼", value: "lab" },
        { key: "办公楼", value: "office" },
        { key: "图书馆", value: "library" },
        { key: "其他", value: "others" },
      ],
      roomTypes: ["教室", "实验室", "办公室", "会议室", "报告厅", "其他"],
      // modal
      addCampusVisible: false,
      addBuildingVisible: false,
      addRoomVisible: false,
      // 规则
      campusFormRules: {
        campusName: [{ required: true, message: "校区名不能为空" }],
      },
      // 表单
      campusForm: {
        campus_name: "",
        org_name: this.orgName,
      },
      buildingForm: {
        building_name: "",
        campus_name: "",
      },
      roomForm: {
        room_number: "",
        room_name: "",
        room_type: "",
        building_name: "",
        campus_name: "",
      },
      campusSelected: "",
      buidingSelected: "",
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      value: undefined,
      campusList: [],
      buildingList: [],
      roomList: [],
      roomNum: 0,
      TypeList: [],
      bulkImport_visible: false,
      spaceName: "",
      colors: [
        "#9FE6B8",
        "#FFDb5C",
        "#FF9F7F",
        "#F87293",
        "#8378EA",
        "#E7bCF3",
        "#96BFFF",
      ],
      // campusName: "",
      // campusId: "",
      activeIndex: "1",
      flag: "",
    };
  },
  computed: {
    ...mapState({
      Tree_spin_status: (state) => state.admin.Tree_spin_status,
      spin_status: (state) => state.admin.spin_status,
      uid: (state) => state.public.uid,
      oid: (state) => state.public.oid,
      orgName: (state) => state.public.orgName,
    }),
  },
  methods: {
    async submitAddRoom() {
      try {
        const url = `/pc/v1/rooms`;
        const requestBody = { ...this.roomForm, org_name: this.orgName };
        console.log(
          "🚀 ~ file: Space.vue ~ line 284 ~ submitAddRoom ~ requestBody",
          requestBody
        );
        const data = await axiosInstance.post(url, requestBody);

        this.$message.info("添加成功");
        this.addRoomVisible = false;
        // 重新加载选择树
      } catch (err) {
        this.$message.error("添加失败");
        this.addRoomVisible = false;
        console.log(err);
      }
    },
    async submitAddCampus() {
      try {
        const url = `/pc/v1/campus`;
        const requestBody = { ...this.campusForm, org_name: this.orgName };
        const data = await axiosInstance.post(url, requestBody);
        this.$message.info("添加成功");
        this.addCampusVisible = false;
        // 重新加载选择树
        this.spaceList();
        this.$forceUpdate();
      } catch (err) {
        this.$message.error("添加失败");
        this.addCampusVisible = false;
        console.log(err);
      }
    },
    async submitAddBuilding() {
      try {
        const url = `/pc/v1/building`;
        const requestBody = { ...this.buildingForm, org_name: this.orgName };
        const data = await axiosInstance.post(url, requestBody);
        this.$message.info("添加成功");
        this.addBuildingVisible = false;
        // 重新加载选择树
        this.spaceList();
      } catch (err) {
        this.$message.error("添加失败");
        this.addBuildingVisible = false;
        console.log(err);
      }
    },
    async campusAndBuilding(params, label) {
      params = params.split(":");
      this.roomForm.campus_name = params[0];
      this.roomForm.building_name = params[1];
      this.selectValue = label;
    },
    async onChange(value, label) {
      this.flag = value;
      if (this.flag.slice(-1) == "#") {
        let payload = {};
        this.activeIndex = "1";
        let temp = this.flag.slice(0, -1);
        payload = { campus_id: temp };
        this.getSpaceFromCondition(payload, 1);
      } else {
        let payload = {};
        this.activeIndex = "2";
        let dataArray = this.flag.split(":");
        payload = {
          campus_id: dataArray[0],
          building_id: dataArray[1],
        };
        this.getSpaceFromCondition(payload, 2);
      }
      this.value = label;
    },
    async spaceList() {
      let queryString = "";
      const url = "/pc/v1/campus" + queryString;
      try {
        this.$store.dispatch("admin/change_Tree_spin_status", true);
        const { data } = await axiosInstance.get(url);
        this.$store.dispatch("admin/change_Tree_spin_status", false);
        this.campusList = data.data.campus;
        for (let i = 0; i < this.campusList.length; i++) {
          this.campusList[i].isEditing = false;
        }
        console.log(
          "🚀 ~ file: Space.vue ~ line 362 ~ spaceList ~ this.campusList",
          this.campusList
        );
      } catch (err) {
        console.log(err);
      }
    },
    callback(key) {
      // console.log(key);
    },
    async getSpaceFromCondition(payload, type) {
      let queryString = "";
      Object.keys(payload).forEach((key) => {
        queryString += key + "=" + payload[key] + "&";
      });
      queryString = "?" + queryString.slice(0, -1);
      const url = "/pc/v1/rooms/getRoomByCampusOrBuilding" + queryString;
      try {
        this.$store.dispatch("admin/change_spin_status", true);
        const { data } = await axiosInstance.get(url);
        console.log(
          "🚀 ~ file: Space.vue ~ line 371 ~ getSpaceFromCondition ~ data",
          data
        );
        this.buildingSelected = data.data;
        this.$store.dispatch("admin/change_spin_status", false);
        if (type == 1) {
          this.buildingList = data.data.buildings;
        } else if (type == 2) {
          this.roomList = data.data.rooms;
        }
      } catch (err) {
        console.log(err);
      }
    },
    campusSelect(campus, index) {
      let campusAll = document.getElementsByName("campusBtn");
      campusAll[index].className = "sp_right_item_campusBtnSelect";
      for(let i = 0; i < this.campusList.length; i++) {
        if( i != index) {
          campusAll[i].className = "sp_right_item_campusBtn";
        }
      }
      this.getSpaceFromCondition({ campus_id: campus._id }, 1);
      this.campusSelected = campus;
      this.buildingForm.campus_name = campus.campus_name;
      this.roomList = [];
    },
    editCampus(index) {
      this.campusList[index].isEditing = true;
    },
    async endEditCampus(index, campus) {
      let url = `pc/v1/campus/${campus._id}`;
      try {
        await axiosInstance.patch(url, campus);
        this.$message.info("编辑成功");
        this.campusList[index].isEditing = false;
        this.$forceUpdate();
      } catch (err) {
        console.log(err);
        this.$message.error("编辑失败");
      }
    },
    async deleteCampus(index, campus) {
      let url = `pc/v1/campus/${campus._id}`;
      try {
        await axiosInstance.delete(url, campus);
        this.$message.info("删除成功");
        this.campusList.splice(index, 1);
        this.$forceUpdate();
      } catch (err) {
        console.log(err);
        this.$message.error("删除失败");
      }
    },
    fatherEmit(data) {
      let payload = {};
      payload = {
        campus_id: this.campusSelected._id,
        building_id: data.building_id,
      };
      let build;
      for (let i = 0; i < this.buildingList.length; i++) {
        if (this.buildingList[i]._id == data.building_id) {
          build = this.buildingList[i];
        }
      }
      build.building_name = data.building_name;
      this.buildingList.splice(0, this.buildingList.length);
      this.buildingList.splice(0, 0, build);
      this.getSpaceFromCondition(payload, 2);
      this.selectValue = data.building_name;
    },
    /*
    async getSpace() {
      let url = "/pc/v1/rooms";
      let Room = this.roomList;
      try {
        const { data } = await axiosInstance.get(url);
        console.log(data);
        Room = data.rooms;
        this.roomNum = Room.length;
        let roomList = [];
        let roomtypeList = [];
        let buildingList = [];
        Room.forEach((item, index) => {
          roomtypeList.push(item.room_type);
          buildingList.push(item.building_name);
          console.log(item.room_type);
          // console.log(item.building_name);
        });
        let x = new Set(roomtypeList);
        this.TypeList = [...x];
        console.log(this.TypeList);
        // this.typeNum = [...x].length;
        let y = new Set(buildingList);
        this.BuildingList = [...y];
        console.log([...y]);
        // this.buildingNum = [...y].length;
        console.log(Room);
      } catch (error) {
        console.log(error);
      }
    },*/
    showDeleteConfirm(deleteList) {
      console.log(deleteList);
      deleteList.length == 0
        ? this.$message.info("请选中要删除的项")
        : this.$confirm({
            title: "确认删除吗",
            content: "数据删除后不可恢复",
            okText: "确定",
            okType: "danger",
            cancelText: "取消",
            onOk() {
              console.log(deleteList);
              //post deleteList
            },
            onCancel() {
              console.log("Cancel");
            },
          });
    },
  },
  mounted() {
    //获取下拉列表数据
    this.spaceList();
    // this.getSpace();
  },
};
</script>

<style lang="scss">
.class-card {
  padding-left: 20px;
}

.container {
  padding: 10px;
  height: 100%;
}

.editText {
  border: none;
  border-bottom: 1px solid #4abac4;
  outline: none;
  background-color: rgba(0, 0, 0, 0);
  width: 130px;
  margin: 0 0 14px 0;
  text-align: center;
}
</style>
